package com.sy.netty.c3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Author yumax
 * @Date 2024 01 08 09 36
 **/
@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {

        final DefaultEventLoopGroup group = new DefaultEventLoopGroup();
        new ServerBootstrap()
                // boss 和 worker
                // boos只负责ServerSocketChannel上accept事件，worker只负责scoketChannel上的读写
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel sc) throws Exception {
                        sc.pipeline().addLast("handler1",
                            new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    //super.channelRead(ctx, msg);
                                    final ByteBuf buf = (ByteBuf) msg;
                                    log.debug(buf.toString(StandardCharsets.UTF_8));
                                    ctx.fireChannelRead(msg);// 让消息传递给下一个handler
                                }
                            })
                            .addLast(group, "handler2",new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    final ByteBuf buf = (ByteBuf) msg;
                                    log.debug(buf.toString(StandardCharsets.UTF_8));
                                }
                            })
                            .addLast("h3", new ChannelOutboundHandlerAdapter(){
                                @Override
                                public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                    super.write(ctx, msg, promise);
                                }
                            });
                    }
                })
                .bind(8989);
    }
}
